package com.sixeco.apigetway.handle;

import org.apache.log4j.Logger;

import com.sixeco.apigetway.common.CommonIO;
import com.sixeco.apigetway.common.CommonVar;
import com.sixeco.apigetway.controller.Controller;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * 前置http请求
 * 
 * @author tianzhenjiu
 *
 */
public class AbHttpHandle extends ChannelInboundHandlerAdapter {

	Logger logger = Logger.getLogger(getClass());
	
	
	final Controller controller;
	

	public AbHttpHandle(com.sixeco.apigetway.controller.Controller controller) {
		super();
		this.controller = controller;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		if (!(msg instanceof HttpRequest)) {

			CommonIO.getInstance().writeMsgAndClose(ctx.channel(), CommonVar.createBadRequest(null));
			return;
		}

		HttpRequest request = (HttpRequest) msg;

		/**
		 * 	只允许get 和POST和option
		 */
		if (request.method() != HttpMethod.POST
				&& request.method() != HttpMethod.OPTIONS
				&& request.method() != HttpMethod.GET) {

			CommonIO.getInstance().writeMsgAndClose(ctx.channel(), CommonVar.createBadRequest("仅仅支持get和POST"));
			return;
		}

		controller.service(ctx.channel(), request);
		

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
				HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(CommonVar.HttpChunk.serverError));

		
		CommonIO.getInstance().writeMsgAndClose(ctx.channel(), response);
		logger.warn("请求异常",cause);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
		ctx.flush();
	}

	
}
